/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.NonexistentEntityException;
import entities.Run;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.TestCase;
import entities.Submission;

/**
 *
 * @author santiagobaldrich
 */
public class RunJpaController {

    public RunJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Run run)
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            TestCase testCase = run.getTestCase();
            if (testCase != null)
            {
                testCase = em.getReference(testCase.getClass(), testCase.getIdTestCase());
                run.setTestCase(testCase);
            }
            Submission submission = run.getSubmission();
            if (submission != null)
            {
                submission = em.getReference(submission.getClass(), submission.getIdSubmission());
                run.setSubmission(submission);
            }
            em.persist(run);
            if (testCase != null)
            {
                testCase.getRunCollection().add(run);
                testCase = em.merge(testCase);
            }
            if (submission != null)
            {
                submission.getRunCollection().add(run);
                submission = em.merge(submission);
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Run run) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Run persistentRun = em.find(Run.class, run.getIdRun());
            TestCase testCaseOld = persistentRun.getTestCase();
            TestCase testCaseNew = run.getTestCase();
            Submission submissionOld = persistentRun.getSubmission();
            Submission submissionNew = run.getSubmission();
            if (testCaseNew != null)
            {
                testCaseNew = em.getReference(testCaseNew.getClass(), testCaseNew.getIdTestCase());
                run.setTestCase(testCaseNew);
            }
            if (submissionNew != null)
            {
                submissionNew = em.getReference(submissionNew.getClass(), submissionNew.getIdSubmission());
                run.setSubmission(submissionNew);
            }
            run = em.merge(run);
            if (testCaseOld != null && !testCaseOld.equals(testCaseNew))
            {
                testCaseOld.getRunCollection().remove(run);
                testCaseOld = em.merge(testCaseOld);
            }
            if (testCaseNew != null && !testCaseNew.equals(testCaseOld))
            {
                testCaseNew.getRunCollection().add(run);
                testCaseNew = em.merge(testCaseNew);
            }
            if (submissionOld != null && !submissionOld.equals(submissionNew))
            {
                submissionOld.getRunCollection().remove(run);
                submissionOld = em.merge(submissionOld);
            }
            if (submissionNew != null && !submissionNew.equals(submissionOld))
            {
                submissionNew.getRunCollection().add(run);
                submissionNew = em.merge(submissionNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = run.getIdRun();
                if (findRun(id) == null)
                {
                    throw new NonexistentEntityException("The run with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Run run;
            try
            {
                run = em.getReference(Run.class, id);
                run.getIdRun();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The run with id " + id + " no longer exists.", enfe);
            }
            TestCase testCase = run.getTestCase();
            if (testCase != null)
            {
                testCase.getRunCollection().remove(run);
                testCase = em.merge(testCase);
            }
            Submission submission = run.getSubmission();
            if (submission != null)
            {
                submission.getRunCollection().remove(run);
                submission = em.merge(submission);
            }
            em.remove(run);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Run> findRunEntities()
    {
        return findRunEntities(true, -1, -1);
    }

    public List<Run> findRunEntities(int maxResults, int firstResult)
    {
        return findRunEntities(false, maxResults, firstResult);
    }

    private List<Run> findRunEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Run.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Run findRun(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Run.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getRunCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Run> rt = cq.from(Run.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

}
